<?php
namespace app\modules\controllers;

use yii\web\Controller;
use Yii;
use app\models\Category;
class CategoryController extends Controller{

    /*
     * 分类列表
     */
    public function actionList(){
        $this->layout = 'layout1';
        $model = new Category();
        $list = $model->getTreeList();
        return $this->render('cates',['list'=>$list]);
    }

    /*
     * 添加分类
     */
    public function actionAdd()
    {
        $this->layout = 'layout1';
        $model = new Category();
        $list = $model->getOptions();

        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if($model->add($data)){
//                Yii::$app->session->setFlash('info','添加成功');
                return $this->redirect(['category/list']);
            }
        }
        return $this->render("add",['list'=>$list,'model'=>$model]);
    }


    /*
     * 编辑分类
     */
    public function actionUpdate()
    {
        $this->layout = 'layout1';
        $cateid = Yii::$app->request->get('cateid');
        $model = Category::find()->where('cateid =:id',[':id'=>$cateid])->one();
        $list = $model->getOptions();

        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if($model->load($data) && $model->save()){
                Yii::$app->session->setFlash('info','修改成功');
            }
        }
        return $this->render("add",['list'=>$list,'model'=>$model]);
    }



    /*
     * 删除分类
     */
    public function actionDel()
    {
        try{
            $cateid = Yii::$app->request->get('cateid');
            if(empty($cateid)){
                throw new \Exception('参数错误');
            }
             $data = Category::find()->where('parentid = :pid',[':pid'=>$cateid])->all();
            if($data){
                throw new \Exception('该分类下有子类，不允许删除');
            }

            if(!Category::deleteAll('cateid = :id',[':id'=>$cateid])){
                throw new \Exception('删除失败');
            }else{
                Yii::$app->session->setFlash('info','删除成功');
            }
        }catch (\Exception $e){
            Yii::$app->session->setFlash('info',$e->getMessage());
        }

        return $this->redirect(['category/list']);
    }
}